import React, { useState, useRef } from 'react';
import { history, connect } from 'umi';
import { Card, Button, Form } from 'antd';
import { Col, Row, Tag, Tooltip, Space, notification } from 'antd';
import { goodsType_status } from '@/common/contact'
import DrawerCondition from '@/components/DrawerCondition';
import FormCondition from '@/components/FormCondition';
import EditorForm from '@/components/EditorForm';
import Sku from '../Sku'
import aliOssUpload from '@/utils/aliOssUpload';
import PackagingModel from '@/components/PackagingModel'
import { useEffect } from 'react';
import Commission from '@/components/Commission';
import MainAdminTable from '@/components/MainAdminTable';
import ShareImage from '@/assert/image/shareImageCode.png';
import PopImgShow from '@/components/PopImgShow';
import moment from 'moment'
const CodeInfo = (props) => {
  const { dispatch, visible = {}, onClose, handleCallback, loading, searchLoading } = props;
  const [data, setData] = useState([]);
  const { show = false, detail = {} } = visible;
  const { id, content: oldData = '', showGoodsTagFlag = '1', expressType = 'express', buyLimitFlag = '0', upType = 'now', showFlag = '1', goodsSkuList = [], goodsPropertyList = [], goodsPackageList = [], commission: commissionInfo, helpWorkTypeAdminInfo = {},
    mainWorkTypeAdminInfo = {}, } = detail;
  const [form] = Form.useForm();
  const [commission, setCommission] = useState([]);
  const [MainAdminList, setMainAdminList] = useState([]);
  const [helpAdminList, sethelpAdminList] = useState([]);
  const [list, setList] = useState([]);
  const [content, setContent] = useState(oldData); // 输入的富文本内容
  const [showFlagSet, setShowFlag] = useState({
    showTag: showGoodsTagFlag,
    showbuyLimit: buyLimitFlag,
    showUpType: upType
  })
  const { showTag, showbuyLimit, showUpType } = showFlagSet
  const ref = useRef(null)
  const packagingRef = useRef(null)
  // 新增修改 传id修改 不传id新增
  useEffect(() => {
    if (show) {
      if (id) {
        if (helpWorkTypeAdminInfo.id) {
          sethelpAdminList([helpWorkTypeAdminInfo]);
        }
        if (mainWorkTypeAdminInfo.id) {
          setMainAdminList([mainWorkTypeAdminInfo]);
        }
        if (commissionInfo) {
          setCommission([commissionInfo]);
        }


      }
      setShowFlag({
        showTag: showGoodsTagFlag,
        showbuyLimit: buyLimitFlag,
        showUpType: upType
      })
    }
  }, [show]);
  useEffect(() => {
    fetchData();
  }, []);
  const fetchRoleEdit = () => {
    let goodsSkuList = ref.current.getRowData()
    let goodsPropertyList = ref.current.getPropertyList()
    let goodsPackageList = packagingRef.current.getPackaging()
    let flag = goodsSkuList.reduce((item, val) => {
      if (!item) {
        return item
      }
      else {
        if (!val.price || !val.stock) {
          return false
        }
        else {
          return item
        }
      }

    }, true)
    let property = goodsPropertyList.reduce((item, val) => {
      if (!item) {
        return item
      }
      else {
        if (!val.valueList || !val.name) {
          return false
        }
        else {
          return item
        }
      }

    }, true)
    let goodsPackageFlag = goodsPackageList.reduce((item, val) => {
      if (!item) {
        return item
      }
      else {
        if (val.chooseType === 'any' && (!val.chooseAmount || val.chooseAmount === 0)
        ) {
          console.log(val)
          notification.warning({
            message: '错误提示',
            description: `${goodsType_status[val.packageGoodsType
            ]} 选择任何后 打包数量不能为0`,
          });
          return false
        }
        else {
          return item
        }
      }

    }, true)
    if (!goodsPackageFlag) {
      return
    }
    else if (!flag) {
      return notification.warning({
        message: '错误提示',
        description: '库存或价格不能为0',
      });
    } else if (!property) {
      return notification.warning({
        message: '错误提示',
        description: '规格名称不能为空并且规格值不能为空',
      });
    } else {
      goodsSkuList = goodsSkuList.map(item => {
        return {
          ...item,
          propertyDesc: item.properties.map((val, o) => {
            return val.name + ':' + val.value
          }).toString()
        }
      })
      goodsPropertyList = goodsPropertyList.map(item => {
        const { name, image, valueList } = item
        return {
          propertyName: name,
          propertyCover: image,
          propertyValue: valueList.map(val => { return val.value }).toString()
        }
      })
      form.validateFields().then(async (values) => {
        const { coverVideo, picture, buyLimitFlag = [], categoryId, upDelayTime, upType, shareImg } = values
        let video = await aliOssUpload(coverVideo)
        let img = await aliOssUpload(picture)
        let buyLimit = buyLimitFlag.toString()
        let category = categoryId[categoryId.length - 1]
        let appImg = await aliOssUpload(shareImg);
        let data = {
          id,
          goodsBaseInfo: {
            id,
            ...values,
            content,
            coverVideo: video.toString(),
            picture: img.toString(),
            buyLimitFlag: buyLimit,
            categoryId: category,
            priceType: 'money',
            upDelayTime: upType === 'delay' ? moment(upDelayTime).format('YYYY-MM-DD HH:mm:ss') : '',
            shareImg: appImg.toString(),
            mainAdminId: MainAdminList.reduce((item, val) => {
              return val.id;
            }, ''),
            helpAdminId: helpAdminList.reduce((item, val) => {
              return val.id;
            }, ''),
            commissionId: commission.reduce((item, val) => {
              return val.id;
            }, ''),
          },
          goodsSkuList,
          goodsPropertyList,
          goodsPackageList
        }
        dispatch({
          type: 'commodity/fakeSaveOfflineGoods',
          payload: data,
          callback: () => {
            handleCallback();
            onClose()
          }
        })
      })
    }
  };
  const fetchData = () => {
    dispatch({
      type: 'commodity/fetchListGoodsCategory',
      callback: (e) => {
        setList(e);
      },
    });
  };

  useEffect(() => {
  }, []);
  const modalProps = {
    title: `${id ? '修改' : '新增'}`,
    visible: show,
    onClose,
    width: 980,
    destroyOnClose: true,
    footer: (
      <Button type="primary" loading={loading} onClick={fetchRoleEdit}>
        确定
      </Button>
    ),
  };
  const filterList = (list) => {
    return list.map((item) => {
      const { categoryName: label, id: value, subGoodsCategoryList: children } = item;
      const localItem = {
        label,
        value,
        node: item['node'],
        children: children ? filterList(children) : undefined,
      };
      return localItem;
    });
  };

  const formItems = [
    {
      label: '商品名称',
      name: 'goodsName',
    },
    {
      label: '商品类目',
      name: 'categoryId',
      type: 'cascader',
      select: filterList(list),
    },
    {
      label: '商品图片',
      name: 'picture',
      type: 'upload',
      extra: '建议尺寸1：1，JPG、PNG格式， 图片小于5M，你可以拖拽图片调整顺序，最多上传15张 ',
      maxFile: 15
    },
    {
      label: '主图视频',
      name: 'coverVideo',
      rules: [{ required: false }],
      extra: '视频画面建议尺寸1:1或16:9，时长10-30s，默认优先展示主图视频',
      type: 'videoUpload',
      maxFile: 1
    },
    {
      label: '商品卖点',
      name: 'goodsDesc',
      type: 'textArea',
      rules: [{ required: false }],
      placeholder: '在商品详情页面标题下展示卖点信息，建议80字以内'
    },
    {
      label: '分享图',
      name: 'shareImg',
      extra: (
        <div>
          建议图片分辨率为560x728,分享码位于右下角居下40px居右32px。如下图：
          <div style={{ marginTop: 12 }}>
            <PopImgShow width={80} url={ShareImage}></PopImgShow>
          </div>
        </div>
      ),
      maxFile: 1,
      type: 'upload',
      rules: [{ required: false }],
    },
    {
      type: 'noForm',
      formItem: (
        <Row>
          <Col span={6} style={{ textAlign: 'right' }} className="">商品详情：</Col>
          <Col span={17} className=""> <EditorForm content={oldData} editCallback={(val) => setContent(val)}></EditorForm></Col>
        </Row>
      ),
    },


  ];
  const formItemsGroup1 = [
    {
      label: '是否展示实物商品标签',
      name: 'showGoodsTagFlag',
      type: 'radio',
      onChange: (e) => {
        setShowFlag({
          ...showFlagSet,
          showTag: e.target.value
        })
      },
      select: {
        1: '展示',
        0: '不展示',
      }
    },
    {
      label: '商品标签',
      name: 'goodsTag',
      visible: showTag != '1' ? false : true,
      maxLength: 6
    },
    {
      type: 'noForm',
      rules: [{ required: false }],
      formItem: <Sku form={form} goodsSkuList={goodsSkuList} goodsPropertyList={goodsPropertyList} setData={setData} propsRef={ref} data={data}></Sku>,
    },
    {
      label: '售价',
      name: 'price',
      type: 'number',
      rules: [
        { required: true },
        {
          validator: (rule, value, callback) => {
            const regex = /^\d+(\.\d{1,2})?$/; // 正则表达式，匹配最多两位小数
            if (value && !regex.test(value)) {
              callback('请输入最多两位小数的数字');
            } else {
              callback(); // 校验通过
            }
          },
        },
      ],
      disabled: data.length > 0
    },
    {
      label: '库存',
      name: 'stock',
      type: 'number',
      disabled: data.length > 0
    },
    {
      label: '底价',
      type: 'number',
      rules: [
        {
          validator: (rule, value, callback) => {
            const regex = /^\d+(\.\d{1,2})?$/; // 正则表达式，匹配最多两位小数
            if (value && !regex.test(value)) {
              callback('请输入最多两位小数的数字');
            } else {
              callback(); // 校验通过
            }
          },
        },
      ],
      name: 'oriPrice',
    },
    {
      label: '商品编码',
      rules: [{ required: false }],
      name: 'goodsCode',
    },

  ]
  const formItemsGroup2 = [
    {
      label: '快递类型',
      name: 'expressType',
      select: [{
        label: '物流快递',
        value: 'express',
        disabled: true
      }, {
        label: '到店自提',
        value: 'takeSelf',
        disabled: true
      }],
      type: 'checkbox'
    },
    {
      label: '快递运费',
      name: 'expressPrice',
    },
  ]
  const formItemsGroup3 = [
    {
      type: 'noForm',
      formItem: (
        <PackagingModel defaultDataList={goodsPackageList} ref={packagingRef} detail={detail}> </PackagingModel>
      ),
    },
    {
      label: '限购设置',
      name: 'buyLimitFlag',
      rules: [{ required: false }],
      select: [{
        label: '限购',
        value: '1',
      }],
      onChange: (e) => {
        setShowFlag({
          ...showFlagSet,
          showbuyLimit: e.toString()
        })
      },
      type: 'checkbox'
    },
    {
      label: '限制每人可购买数量',
      name: 'buyLimit',
      type: 'number',
      rules: showbuyLimit !== '1' ? [{ required: false }] : [{ required: true }],
      disabled: showbuyLimit !== '1'
    },
    {
      type: 'noForm',
      formItem: (
        <Commission
          list={commission}
          onChange={(e) => {
            setCommission(e);
          }}
        ></Commission>
      ),
    },
    {
      type: 'noForm',
      formItem: (
        <MainAdminTable
          disabledList={helpAdminList}
          title={'主负责'}
          list={MainAdminList}
          onChange={(e) => {
            console.log(e);
            setMainAdminList(e);
          }}
        ></MainAdminTable>
      ),
    },
    {
      type: 'noForm',
      formItem: (
        <MainAdminTable
          disabledList={MainAdminList}
          title={'协助负责'}
          list={helpAdminList}
          onChange={(e) => {
            sethelpAdminList(e);
          }}
        ></MainAdminTable>
      ),
    },
  ]
  const formItemsGroup4 = [
    {
      label: '上架类型',
      name: 'upType',
      type: 'radio',
      onChange: (e) => {
        setShowFlag({
          ...showFlag,
          showUpType: e.target.value
        })
      },
      select: {
        now: '立刻上架',
        delay: '定时上架',
        off: '暂不上架'
      }
    },
    {
      label: '定时上架时间',
      name: 'upDelayTime',
      type: 'dataPicker',
      format: 'YYYY-MM-DD HH:mm',
      visible: showUpType === 'delay'
    },
    {
      label: '是否显示在店铺',
      name: 'showFlag',
      type: 'radio',
      select: {
        0: '否',
        1: '是',
      },
    },
  ]
  return (
    <>
      <DrawerCondition {...modalProps}>
        <div className='commodity-manage-part'>
          <div className='commodity-part-title'>
            <div className='commodity-title-line'></div>
            <div className='commodity-part-title-word'>基本信息</div>
          </div>
        </div>
        <FormCondition form={form} formItems={formItems} initialValues={detail}></FormCondition>
        <div className='commodity-manage-part'>
          <div className='commodity-part-title'>
            <div className='commodity-title-line'></div>
            <div className='commodity-part-title-word'>商品信息</div>
          </div>
        </div>
        <FormCondition form={form} formItems={formItemsGroup3} initialValues={detail}></FormCondition>
        <div className='commodity-manage-part'>
          <div className='commodity-part-title'>
            <div className='commodity-title-line'></div>
            <div className='commodity-part-title-word'>商品标签</div>
          </div>
        </div>
        <FormCondition form={form} formItems={formItemsGroup1} initialValues={{ ...detail, showGoodsTagFlag }}></FormCondition>


        <div className='commodity-manage-part'>
          <div className='commodity-part-title'>
            <div className='commodity-title-line'></div>
            <div className='commodity-part-title-word'>物流</div>
          </div>
        </div>
        <FormCondition form={form} formItems={formItemsGroup2} initialValues={{ ...detail, expressType }}></FormCondition>
        <div className='commodity-manage-part'>
          <div className='commodity-part-title'>
            <div className='commodity-title-line'></div>
            <div className='commodity-part-title-word'>上架设置</div>
          </div>
        </div>
        <FormCondition form={form} formItems={formItemsGroup4} initialValues={{ ...detail, upType, showFlag }}></FormCondition>
      </DrawerCondition>

    </>
  );
};
export default connect(({ loading }) => ({
  loading: loading.effects['commodity/fakeSaveOfflineGoods'],
}))(CodeInfo);
